package com.fwmagic.flink.window;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

public class EventTimeSessionWindow {
    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);

        //时间设置为EventTime
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        //提取数据中的时间，转为Long类型的时间戳，当作EventTime
        //仅仅是提取时间，不会改变数据
        SingleOutputStreamOperator<String> dataSource = env.socketTextStream("localhost", 8888)
                .assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<String>(Time.seconds(0)) {
            @Override
            public long extractTimestamp(String line) {
                String[] fields = line.split(",");
                return Long.parseLong(fields[0]);
            }
        });

        /**
         * 1583071000,spark,1
         * 1583072000,spark,2
         * 1583077001,spark,3
         * 1583080000,spark,10
         * 1583086000,spark,1
         */
        SingleOutputStreamOperator<Tuple2<String, Integer>> maped = dataSource.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                String[] arr = value.split(",");
                return Tuple2.of(arr[1], Integer.parseInt(arr[2]));
            }
        });

        //分组
        KeyedStream<Tuple2<String, Integer>, Tuple> keyed = maped.keyBy(0);

        //统计数据的EventTime(事件时间)和最后一条数据的事件时间差为5秒时的数据总数
        WindowedStream<Tuple2<String, Integer>, Tuple, TimeWindow> window = keyed.window(EventTimeSessionWindows.withGap(Time.seconds(5)));

        //计数
        SingleOutputStreamOperator<Tuple2<String, Integer>> sumed = window.sum(1);

        sumed.print();

        env.execute("EventTimeSessionWindow");
    }
}
